package com.example.wan1.view.square;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.wan1.R;
import com.example.wan1.adapter.ArticleListAdapter;
import com.example.wan1.base.fragment.SimpleFragment;
import com.example.wan1.bus.RxBus;
import com.example.wan1.constant.Constants;
import com.example.wan1.event.CollectEvent;
import com.example.wan1.model.ArticleBean;
import com.example.wan1.model.common.CommonResList;
import com.example.wan1.utils.ToastUtils;
import com.example.wan1.utils.ToolsUtils;
import com.example.wan1.view.collect.HandleCollectTool;
import com.example.wan1.view.login.UserManager;
import com.example.wan1.view.user.UserCenterActivity;
import com.example.wan1.view.web.JumpTool;
import com.scwang.smart.refresh.header.MaterialHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;

/***
 * @Author: zxd
 * @CreateDate: 2020/6/29 10:42
 * @Description: 广场
 */
public class SquareFragment extends SimpleFragment implements SquareContract.View,
        OnLoadMoreListener, OnRefreshListener {

    @BindView(R.id.srlheader)
    MaterialHeader mSrlheader;
    @BindView(R.id.square_rv)
    RecyclerView mSquareRv;
    @BindView(R.id.srl)
    SmartRefreshLayout mSrl;

    @Inject
    SquarePresenter mPresenter;

    List<ArticleBean> mList;
    ArticleListAdapter mAdapter;

    private int currentPage = 0;//当前页

    @Override
    protected void initData() {
        Log.e("zxd", "initData: square");
        mPresenter.start();
    }

    @Override
    protected void initView() {
        Log.e("zxd", "initView: square");
        showLoading();
        mList = new ArrayList<>();
        mAdapter = new ArticleListAdapter(R.layout.article_item, mList);
        mSquareRv.setAdapter(mAdapter);
        mSquareRv.setLayoutManager(new LinearLayoutManager(getActivity(),
                LinearLayoutManager.VERTICAL, false));

        mSrl.setOnLoadMoreListener(this);
        mSrl.setOnRefreshListener(this);

        mSrl.setEnableRefresh(false);
        mSrl.setEnableLoadMore(false);

        mAdapter.setOnItemClickListener((baseQuickAdapter, view, i) -> {
            JumpTool.goWeb(mContext, mList.get(i).getTitle(), mList.get(i).getLink());
            HandleCollectTool.getInstance().setInfo(mList.get(i), i, Constants.ARTICLE);
        });

        mAdapter.setOnItemChildClickListener((baseQuickAdapter, view12, i) -> {
            switch (view12.getId()) {
                case R.id.article_iv_collect: {
                    if (!UserManager.getInstance().isLogin()) {
                        JumpTool.goLogin(getActivity());
                        return;
                    }
                    ArticleBean articleBean = mList.get(i);
                    HandleCollectTool.getInstance().setInfo(articleBean, i, Constants.ARTICLE);
                    ImageView iv = view12.findViewById(R.id.article_iv_collect);
                    if (articleBean.isCollect()) {
                        HandleCollectTool.getInstance().cancelList();
                        iv.setImageResource(R.mipmap.heart_gray);
                    } else {
                        HandleCollectTool.getInstance().collectIn();
                        iv.setImageResource(R.mipmap.heart_red);
                    }
                }
                break;
                case R.id.article_tv_author:
                    Intent intent = new Intent(getActivity(), UserCenterActivity.class);
                    intent.putExtra("id", mList.get(i).getUserId());
                    intent.putExtra("username", mList.get(i).getShareUser());
                    startActivity(intent);
                    break;
            }
        });

        mSquareRv.addOnScrollListener(mOnScrollListener);
    }

    @Override
    protected int initLayoutRes() {
        return R.layout.fragment_square;
    }

    @Override
    public void onSuccess(CommonResList<ArticleBean> data) {
        Log.e("zxd", "onSuccess: square");
        mSrl.setEnableRefresh(true);
        mSrl.setEnableLoadMore(true);
        if (data.isOver()) {
            mAdapter.loadMoreEnd();//我是有底线的~
        }
        //currentPage 请求0返回1
        currentPage = data.getCurPage();
        mAdapter.addData(data.getDatas());
        mAdapter.notifyDataSetChanged();
        hideLoading();
    }

    @Override
    public void onFailure(String msg) {
        ToastUtils.showToast(msg);
        showError();
        mSrl.setEnableLoadMore(false);
        mSrl.setEnableRefresh(false);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        mSquareRv.postDelayed(() -> {
            mPresenter.getArticleList(currentPage);
            mSrl.finishLoadMore(true);
        }, 200);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        mSquareRv.postDelayed(() -> {
            mPresenter.start();
            mSrl.finishRefresh(true);
        }, 200);
    }

    public void notifyItemCollect() {
        if (mSquareRv.getAdapter() == null)
            mAdapter.bindToRecyclerView(mSquareRv);
        int pos = HandleCollectTool.getInstance().getPosition();
        mAdapter.notifyItemChanged(pos);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        RxBus.getDefault().subscribeSticky(mContext, new RxBus.Callback<CollectEvent>() {
            @Override
            public void onEvent(CollectEvent collectEvent) {
                if (Constants.ARTICLE.equals(collectEvent.getType()))
                    notifyItemCollect();
            }
        });

        RxBus.getDefault().subscribe(mContext, new RxBus.Callback<String>() {
            @Override
            public void onEvent(String s) {
                if (s.equals("theme_color")) {
                    int color = ToolsUtils.getThemeColor(getActivity());
                } else if (s.equals("cancelArticle")) {
                    mList.clear();
                    mPresenter.start();
                }
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        RxBus.getDefault().unregister(mContext);
    }
}
